package com.itcast.solr.controller;

import com.itcast.solr.dao.ItemSolrDao;
import com.itcast.solr.pojo.PageResult;
import com.itcast.solr.pojo.TbItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/solr")
public class ItemSolrController {
    @Autowired
    private ItemSolrDao itemSolrDao;

    @RequestMapping("/findall")
    public List<TbItem> findAll(String title){
        return itemSolrDao.findByTitle(title);
    }

    @RequestMapping("/findpage")
    public PageResult findPageData(@RequestBody Map<String,String> searchMap, Integer page, Integer size){
        Pageable pageable = new PageRequest(page-1,size);
        if(searchMap == null || StringUtils.isEmpty(searchMap.get("keywords"))){

            Page<TbItem> pageData = itemSolrDao.findAll(pageable);
            return  new PageResult(pageData.getTotalElements(),pageData.getContent());

        }else {

            HighlightPage<TbItem> itemHighlightPage = itemSolrDao.findHighLightByTitle(searchMap.get("keywords"),pageable);
            //循环结果，将高亮显示的内容进行修改
            for (TbItem item : itemHighlightPage.getContent()){
                for (HighlightEntry.Highlight highlight : itemHighlightPage.getHighlights(item)) {
                    if(highlight.getField().getName().equals("item_title")){
                        item.setTitle(highlight.getSnipplets().get(0));
                    }
                    if (highlight.getField().getName().equals("item_category")){
                        item.setCategory(highlight.getSnipplets().get(0));
                    }
                }
            }
            return new PageResult(itemHighlightPage.getTotalElements(),itemHighlightPage.getContent());
        }

    }
}
